<template>
  <div class="artical-edit column">
    <div class="title row">
      <h3>竞赛项目编辑</h3>
    </div>
    <el-form
      :model="formData"
      ref="formData"
      label-width="100px"
      label-position="top"
      class="formData"
      :rules="rules"
    >
      <el-form-item label="竞赛名称：" prop="compName">
        <el-input
          placeholder="请输入竞赛名称："
          v-model="formData.compName"
          maxlength="50"
        ></el-input>
      </el-form-item>
      <el-form-item label="竞赛类型：" prop="category">
        <el-select v-model="formData.category" placeholder="请选择文章类型">
          <el-option label="计算机类" value="计算机类"></el-option>
          <el-option label="英语类" value="英语类"></el-option>
          <el-option label="其他类" value="其他类"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择时间：" prop="dateTime">
        <el-date-picker
          v-model="formData.dateTime"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="所属学校：">
        <el-select v-model="formData.schoolName" disabled placeholder="">
        </el-select>
      </el-form-item>
      <el-form-item label="选择负责人：" prop="sponsor">
        <el-select v-model="formData.sponsor" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="上传模板：">
        <!-- 上传模板 -->
        <el-input v-model="formData.tempUrl" :disabled="true"></el-input>
        <el-upload
          class="upload"
          :action="actionUrl"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          :on-success="handleSuccess"
          :limit="1"
          :on-exceed="handleExceed"
          :file-list="fileList"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">
            只能上传DOC/DOCX文件，且不超过500kb
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章内容：">
        <Tinymce ref="tinymce" v-model="formData.content"></Tinymce>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('formData')"
          >确认</el-button
        >
        <el-button @click="resetForm('formData')">重置</el-button>
        <el-button @click="cancel('formData')">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import CompApi from "@/api/competition";
import Tinymce from "@/components/Tinymce";
import ImageUpload from "@/components/ImageUpload/index";
export default {
  name: "editArtical",
  components: { Tinymce, ImageUpload },
  data() {
    var checkCompName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入竞赛名称"));
      } else {
        callback();
      }
    };
    var checkCategory = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择竞赛类型"));
      } else {
        callback();
      }
    };
    var checkDateTime = (rule, value, callback) => {
      if (value === "" || value == null) {
        callback(new Error("请选择竞赛时间"));
      } else {
        callback();
      }
    };
    var checkSponsor = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择负责人"));
      } else {
        callback();
      }
    };
    return {
      // 上传地址
      actionUrl: process.env.VUE_APP_SERVICE_URL + "/upload/template",
      //时间选择
      formData: {
        compId: null,
        compName: "",
        category: "",
        dateTime: null,
        sponsor: "",
        schoolName: "",
        tempUrl: "",
        content: "",
      },
      options: [
        {
          value: "李叉叉",
          label: "李叉叉",
        },
        {
          value: "金叉叉",
          label: "金叉叉",
        },
        {
          value: "陈叉叉",
          label: "陈叉叉",
        },
        {
          value: "吴叉叉",
          label: "吴叉叉",
        },
      ],
      rules: {
        compName: [{ validator: checkCompName, trigger: "blur" }],
        category: [{ validator: checkCategory, trigger: "blur" }],
        dateTime: [{ validator: checkDateTime, trigger: "blur" }],
        sponsor: [{ validator: checkSponsor, trigger: "blur" }],
      },
      // 上传
      fileList: [
        // {
        //   name: "food.jpeg",
        //   url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
        // },
      ],
    };
  },
  watch: {},
  mounted() {
    this.getEditData();
  },
  computed: {
    userInfo() {
      return JSON.parse(localStorage.getItem("userInfo"));
    },
  },
  methods: {
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.formData.content = "";
      this.formData.tempUrl = "";
      this.fileList = [];
    },
    getEditData() {
      if (localStorage.getItem("currentCompData") != null) {
        this.formData = JSON.parse(localStorage.getItem("currentCompData"));
        this.formData.dateTime = this.formData.dateTime.split(",");
        if (this.formData.tempUrl != null && this.formData.tempUrl != "") {
          this.fileList.push({
            name: this.formData.tempUrl.split("/")[
              this.formData.tempUrl.split("/").length - 1
            ],
            url: this.formData.tempUrl,
          });
        }
      } else {
        this.formData.schoolName = this.userInfo.schoolName;
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var formData = new FormData();
          formData.append("compName", this.formData.compName);
          formData.append("category", this.formData.category);
          formData.append("dateTime", this.formData.dateTime);
          formData.append("sponsor", this.formData.sponsor);
          formData.append("schoolName", this.formData.schoolName);
          formData.append("content", this.formData.content);
          formData.append("tempUrl", this.formData.tempUrl);
          if (this.formData.compId == null) {
            CompApi.addComp(formData).then((res) => {
              this.$message({
                message: "添加成功",
                type: "success",
              });
              this.resetForm(formName);
            });
          } else {
            formData.append("compId", this.formData.compId);
            CompApi.editComp(formData).then((res) => {
              this.$message({
                message: "编辑成功",
                type: "success",
              });
              this.$router.go(-1);
            });
          }
          // this.$router.push({path: "/userCenter/comp"})
        } else {
          return false;
        }
      });
    },
    cancel(formName) {
      this.resetForm(formName);
      this.$router.go(-1);
    },
    //时间格式化
    dateFormat(fmt, date) {
      let ret;
      const opt = {
        "Y+": date.getFullYear().toString(), // 年
        "m+": (date.getMonth() + 1).toString(), // 月
        "d+": date.getDate().toString(), // 日
        // "H+": date.getHours().toString(), // 时
        // "M+": date.getMinutes().toString(), // 分
        // "S+": date.getSeconds().toString(), // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
      };
      for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
          fmt = fmt.replace(
            ret[1],
            ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0")
          );
        }
      }
      return fmt;
    },
    // 上传下载
    // 	文件上传成功时的钩子
    handleSuccess(response, file, fileList) {
      console.log("上传成功:", response);
      this.formData.tempUrl = response.data;
      var fileList = [];
      var src = response.data;
      fileList.push({
        name: src.split("/")[src.split("/").length - 1],
        url: src,
      });
      this.fileList = fileList;
    },
    // 文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      console.log("handleRemove", file, fileList);
      this.formData.tempUrl = "";
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePreview(file) {
      console.log(file);
      this.$confirm("此操作将下载该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          window.open(file.url, "_blank");
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消下载",
          });
        });
    },
    // 文件超出个数限制时的钩子
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    // 删除文件之前的钩子，参数为上传的文件和文件列表，若返回 false 或者返回 Promise 且被 reject，则停止删除。
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
  },
};
</script>

<style scoped>
.artical-edit {
  width: 1000px;
  box-sizing: border-box;
  padding: 35px 0 0 0;
}
.artical-edit .title {
  align-items: center;
}
.artical-edit .title h3 {
  color: #343739;
  font-size: 24px;
  display: inline-block;
  margin: 0 15px 15px 0;
  font-weight: normal;
  vertical-align: middle;
}
.upload {
}
</style>